import { UserProfile } from '@/types/data'
import { RootState } from '@/types/store'
import { Input, NavBar, TextArea } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'

import styles from './index.module.scss'

type PropsType = {
  closePopup: () => void
  type: '' | 'name' | 'intro'
  update: (val: string, type: string) => void
}

const EditInput = ({ closePopup, type, update }: PropsType) => {
  const userProfile = useSelector<RootState, UserProfile>((state) => {
    return state.profile.userProfile
  })

  // 创建一个状态 控制输入框、textarea
  // useState的初始值 只在 组件初次渲染时有用！！！
  const [value, setValue] = useState(() =>
    type === 'name' ? userProfile.name : userProfile.intro
  )

  const inputRef = useRef<InputRef>(null) // Input组件的ref
  const textRef = useRef<TextAreaRef>(null) // TextArea组件的ref

  useEffect(() => {
    inputRef.current?.focus()
    textRef.current?.focus()
  }, [])

  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        right={
          <span className="commit-btn" onClick={() => update(value, type)}>
            提交
          </span>
        }
        onBack={() => {
          // console.log(111)
          // 子传父
          closePopup()
        }}
      >
        编辑{type === 'name' ? '昵称' : '简介'}
      </NavBar>

      <div className="edit-input-content">
        <h3>{type === 'name' ? '昵称' : '简介'}</h3>

        {type === 'name' ? (
          <div className="input-wrap">
            <Input
              ref={inputRef}
              value={value}
              onChange={(val) => {
                // val 不是事件对象 就是用户输入的值！！
                // console.log(val)
                setValue(val)
              }}
              placeholder="请输入"
            />
          </div>
        ) : (
          <TextArea
            ref={textRef}
            value={value}
            onChange={(val) => setValue(val)}
            placeholder="请输入简介"
            className="textarea"
            maxLength={99}
            showCount
          ></TextArea>
        )}
      </div>
    </div>
  )
}

export default EditInput
